package com.erlang.spring.factory;

import com.erlang.spring.proxy.CglibProxy;
import com.erlang.spring.proxy.JdkProxy;
import org.springframework.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;

/**
 * @Description：工厂bean的动态代理
 */
public class BeanProxyFactory {
	//我为谁干活
    private Object targetClass;

    //传入目标类
    public BeanProxyFactory(Object targClass) {
        this.targetClass = targClass;
    }

    public Object getBean() {
        //获得对应类的接口
        Class<?>[] interfaces = targetClass.getClass().getInterfaces();
        Object object = null;
        //接口数目大于0
        if (interfaces.length>0){
            //jdk代理
            JdkProxy jdkProxy = new JdkProxy(targetClass);
            object = Proxy.newProxyInstance(targetClass.getClass().getClassLoader(), interfaces, jdkProxy);
        }else {
            //cglib代理
            CglibProxy cglibProxy  = new CglibProxy(targetClass);
            object = Enhancer.create(targetClass.getClass(), cglibProxy);
        }
        return object;
    }
}
